package com.zohnblog.web.admin;

import com.github.pagehelper.PageInfo;
import com.zohnblog.model.ResponseData.ArticleResponseData;
import com.zohnblog.model.ResponseData.StaticticsBo;
import com.zohnblog.model.domain.Article;
import com.zohnblog.model.domain.Comment;
import com.zohnblog.model.domain.IPBanMode;
import com.zohnblog.model.domain.User;
import com.zohnblog.service.*;
import com.zohnblog.service.impl.WebStatisticServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/*
* 后台管理模块
* */
@Controller
@RequestMapping("/admin")
public class AdminController {
    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private ISiteService siteServiceImpl;

    @Autowired
    private IArticleService articleServiceImpl;

    @Autowired
    private ICommentService commentService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IIPBanModeService ipBanModeService;
    @Autowired
    WebStatisticServiceImpl webStatisticService;

    //管理中心起始页
    @GetMapping(value = {"","/index"})
    public String index(HttpServletRequest request){
//        String ip = request.getRemoteAddr();
//        logger.info("进入管理中心起始页，ip:" + ip);
        // 获取最新的5篇博客、评论以及统计数据
        List<Article> articles = siteServiceImpl.recentArticle(5);
        List<Comment> comments = siteServiceImpl.recentComments(5);
        StaticticsBo staticticsBo = siteServiceImpl.getStatistics();
        // 向Request域中存储数据
        request.setAttribute("comments",comments);
        request.setAttribute("articles",articles);
        request.setAttribute("statistics",staticticsBo);
        return "back/index";
    }

    // 向文章发表页面跳转
    @GetMapping(value = "/article/toEditPage")
    public String newArticle(HttpServletRequest request){
//        String ip = request.getRemoteAddr();
//        logger.info("向文章发表页面跳转，ip:" + ip);
        return "back/article_edit";
    }

    // 发表文章
    @PostMapping(value = "/article/publish")
    @ResponseBody
    public ArticleResponseData publishArticle(HttpServletRequest request, Article article){
//        String ip = request.getRemoteAddr();
//        logger.info("发表文章，ip:" + ip);
        if (StringUtils.isBlank(article.getCategories())){
            article.setCategories("默认分类");
        }
        try{
            articleServiceImpl.publish(article);
            logger.info("文章发布成功");
            return ArticleResponseData.ok();
        }catch (Exception e){
            logger.error("文章发布失败，错误信息：" +e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    // 跳转到后台文章列表页面
    @GetMapping(value = "/article")
    public String articleList(@RequestParam(value = "page",defaultValue="1") int page,
                        @RequestParam(value = "count",defaultValue = "10") int count,
                        HttpServletRequest request){
//        String ip = request.getRemoteAddr();
//        logger.info("跳转到后台文章列表页面，ip:" + ip);
        PageInfo<Article> pageInfo = articleServiceImpl.selectArticleWIthPage(page,count);
        request.setAttribute("articles",pageInfo);
        return "back/article_list";
    }

    // 向文章修改页面跳转
    @GetMapping(value = "/article/{id}")
    public String editArticle(@PathVariable("id") String id, HttpServletRequest request){
//        String ip = request.getRemoteAddr();
//        logger.info("向文章修改页面跳转，ip:" + ip);
        Article article = articleServiceImpl.selectArticleWithId(Integer.parseInt(id));
        request.setAttribute("contents", article);
        request.setAttribute("categories", article.getCategories());
        return "back/article_edit";
    }

    // 修改处理文章
    @PostMapping(value = "/article/modify")
    @ResponseBody
    public ArticleResponseData modifyArticle(Article article, HttpServletRequest request){
        try{
            articleServiceImpl.updateArticleWithId(article);
            logger.info("文章更新成功");
            return ArticleResponseData.ok();
        } catch (Exception e){
            logger.error("文章更新失败，错误信息：" + e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    // 文章删除
    @PostMapping(value = "/article/delete")
    @ResponseBody
    public ArticleResponseData delete(@RequestParam int id, HttpServletRequest request){
        try{
//            String ip = request.getRemoteAddr();
//            logger.info("文章删除，ip:" + ip);
//            // 获取当前登录用户
//            org.springframework.security.core.userdetails.User user=(org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//            if (!"admin".equals(user.getUsername())) {
//                logger.info("游客账号无法进行删除评论操作");
//                return ArticleResponseData.fail("游客账号无法进行删除评论操作");
//            }
            articleServiceImpl.deleteArticleWithId(id);
            logger.info("文章删除成功");
            return ArticleResponseData.ok();
        } catch (Exception e){
            logger.error("文章删除失败，错误信息：" +e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    // 跳转到后台评论列表
    @GetMapping(value = "/comment")
    public String commentList(@RequestParam(value = "page",defaultValue="1") int page,
                        @RequestParam(value = "count",defaultValue = "10") int count,
                        HttpServletRequest request){
        PageInfo<Comment> pageInfo = commentService.getAllComments(page,count);
        request.setAttribute("comments",pageInfo);
        return "back/comment_list";
    }

    // 删除文章评论
    @PostMapping(value = "/comment/delete")
    @ResponseBody
    public ArticleResponseData deleteComment(@RequestParam int id, @RequestParam int aid, HttpServletRequest request){
        try{
            String ip = request.getRemoteAddr();
            //           logger.info("删除文章评论，ip:" + ip);
//            // 获取当前登录用户
//            org.springframework.security.core.userdetails.User user=(org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//            if (!"admin".equals(user.getUsername())) {
//                logger.info("游客账号无法进行删除评论操作");
//                return ArticleResponseData.fail("游客账号无法进行删除评论操作");
//            }
            commentService.deleteComment(id,aid);
            logger.info("评论删除成功");
            return ArticleResponseData.ok();
        } catch (Exception e){
            logger.error("评论删除失败，错误信息：" +e.getMessage());
            return ArticleResponseData.fail("评论删除失败，错误信息：" +e.getMessage());
        }
    }

//    // 跳转到后台用户列表页面
//    @GetMapping(value = "/user")
//    public String userList(@RequestParam(value = "page",defaultValue="1") int page,
//                        @RequestParam(value = "count",defaultValue = "10") int count,
//                        HttpServletRequest request){
//        String ip = request.getRemoteAddr();
//        logger.info("跳转到后台用户列表页面，ip:" + ip);
//        PageInfo<User> pageInfo = userService.selectAllUser(page,count);
//        request.setAttribute("users",pageInfo);
//        return "back/user_list";
//    }

    //IP封禁模式列表
    @GetMapping(value = "/ipbanmode")
    public String ipBanMode(@RequestParam(value = "page",defaultValue="1") int page,
                            @RequestParam(value = "count",defaultValue = "10") int count,
                            HttpServletRequest request){
        PageInfo<IPBanMode> pageInfo = ipBanModeService.getAllMode(page,count);
        Integer webRequests = webStatisticService.getRequestsByDate(new Date());
        request.setAttribute("ipBanModes", pageInfo);
        request.setAttribute("webRequests", webRequests);
        return "back/ip_ban_setting";
    }

    // 创建IP封禁模式
    @PostMapping(value = "/ipbanmode/create")
    @ResponseBody
    public ArticleResponseData createIPBanMode(IPBanMode ipBanMode){
        try{
            ipBanModeService.createMode(ipBanMode);
            logger.info("IP封禁模式创建成功");
            return ArticleResponseData.ok();
        }catch (Exception e){
            logger.error("IP封禁模式创建失败，错误信息：" +e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    // 创建IP封禁模式
    @PostMapping(value = "/ipbanmode/open")
    @ResponseBody
    public ArticleResponseData openIPBanMode(@RequestParam int id){
        try{
            ipBanModeService.openMode(id);
            logger.info("开启IP封禁模式成功");
            return ArticleResponseData.ok();
        }catch (Exception e){
            logger.error("开启IP封禁模式失败，错误信息：" +e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    // 删除一个IP封禁模式
    @PostMapping(value = "/ipbanmode/delete")
    @ResponseBody
    public ArticleResponseData deleteIPBanMode(@RequestParam int id){
        try{
            ipBanModeService.deleteMode(id);
            logger.info("删除成功");
            return ArticleResponseData.ok();
        }catch (Exception e){
            logger.error("删除失败，错误信息：" +e.getMessage());
            return ArticleResponseData.fail();
        }
    }

    // 关闭所有IP封禁模式
    @PostMapping(value = "/ipbanmode/closeall")
    @ResponseBody
    public ArticleResponseData closeIPBanMode(){
        try{
            ipBanModeService.closeAllMode();
            logger.info("IP封禁模式创建成功");
            return ArticleResponseData.ok();
        }catch (Exception e){
            logger.error("IP封禁模式创建失败，错误信息：" +e.getMessage());
            return ArticleResponseData.fail();
        }
    }
}
